package com.manlu.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Auther 漫路h
 * Created by 2020-05-03 17:49
 */
@Service
public class ImageService {
    public String addImage(MultipartFile file, HttpServletRequest request) {
        //上传图片
        //编写图片上传的业务逻辑方法
        if (file != null) {
            //1.获取图片名称
            String filename = file.getOriginalFilename();
            System.out.println(filename);
            //2.获取图片扩展名
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            //3.生成图片名称
            String imgName = UUID.randomUUID() + "";
            //4.生成图片的存放在服务器的路径
            String path = imgName + "." + ext;
            //5.获取服务器的绝对路径进行保存图片
            //        String url = request.getServletContext().getRealPath("") + path;
            String url = "/upload/" + path;
            //6. 图片上传
            try {
                file.transferTo(new File("E:\\MyProject\\blogImage\\" + path));
                //添加成功
                return ""+url;
            } catch (IOException e) {
                return "err"+e.getMessage();
                //photoCategoryMapper.deleteByPrimaryKey(cid);
            }
        }
        return "err";
    }
}
